﻿using System;
using Resources;
using Wicresoft.RDW.Presentation;
using Wicresoft.RDW.Utility;
using System.Configuration;
using System.IO;
using System.Linq;

namespace Wicresoft.RDW.Product
{
    public partial class Update : BasePage_BackEnd
    {

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (string.Equals(GetQueryString("pagestatus"), "edit", StringComparison.CurrentCultureIgnoreCase))
                {
                    PageStatus = Utility.PageStatus.Edit;
                    var p = ProductPresent.GetById(Id);
                    if (p != null)
                    {
                        var lab = LabPresent.GetById(p.LabId);
                        var loc = LocationPresent.GetById(lab.LocationId);
                        var reslist = LabPresent.GetList(g => g.LocationId == lab.LocationId);
                        ucLocationLab.LocationValue = lab.LocationId.ToString();
                        ucLocationLab.LabValue = lab.LabId.ToString();
                        txtChName.Text = p.Name_CN;
                        txtEnName.Text = p.Name_EN;
                        txtDemoTypeCN.Text = Server.HtmlDecode(p.DemoType_CN);
                        txtDemoContenCN.Text = Server.HtmlDecode(p.DemoContent_CN);
                        txtDemoStepCN.Text = Server.HtmlDecode(p.DemoStep_CN);
                        txtKeyCommentsCN.Text = Server.HtmlDecode(p.KeyComments_CN);
                        txtEquipmentCN.Text = Server.HtmlDecode(p.Equipment_CN);
                        txtDemoTypeEN.Text = Server.HtmlDecode(p.DemoType_EN);
                        txtDemoContenEN.Text = Server.HtmlDecode(p.DemoContent_EN);
                        txtDemoStepEN.Text = Server.HtmlDecode(p.DemoStep_EN);
                        txtKeyCommentsEN.Text = Server.HtmlDecode(p.KeyComment_EN);
                        txtEquipmentEN.Text = Server.HtmlDecode(p.Equipment_EN);
                        chkChinese.Checked = p.ChineseIntroduce;
                        chkEnglish.Checked = p.EnglishIntroduce;
                        rbtnActive.Checked = p.Status == ((int)(ProductStatus.Active)) ? true : false;
                        rbtnInactive.Checked = p.Status == ((int)(ProductStatus.Inactive)) ? true : false;
                        PageStatus = Utility.PageStatus.Edit;
                    }
                    else { this.phmain.Visible = false; }
                }
                else if (string.Equals(GetQueryString("pagestatus"), "new", StringComparison.CurrentCultureIgnoreCase))
                {
                    txtChName.Text = string.Empty;
                    txtEnName.Text = string.Empty;
                    txtDemoTypeCN.Text = string.Empty;
                    txtDemoContenCN.Text = string.Empty;
                    txtDemoStepCN.Text = string.Empty;
                    txtKeyCommentsCN.Text = string.Empty;
                    txtEquipmentCN.Text = string.Empty;
                    txtDemoTypeEN.Text = string.Empty;
                    txtDemoContenEN.Text = string.Empty;
                    txtDemoStepEN.Text = string.Empty;
                    txtKeyCommentsEN.Text = string.Empty;
                    txtEquipmentEN.Text = string.Empty;
                    rbtnActive.Checked = true;
                    PageStatus = Utility.PageStatus.New;
                }
                else
                {
                    this.phmain.Visible = false;
                }
            }
        }

        public override void InitControlResource()
        {
            btnSubmitPro.Text = ManageResource.mgr_btnOK;
            btnCancel.Text = ManageResource.mgr_btnCancel;
            lblActive.Text = NameResource.Product_Status_Active;
            lblInactive.Text = NameResource.Product_Status_Inactive;
            lblChinese.Text = NameResource.Language_CN_Label;
            lblEnglish.Text = NameResource.Language_EN_Label;
            revtxtDemoContenCN.Text = string.Format(NameResource.OverMaxLength, "1000");
            revtxtDemoStepCN.Text = string.Format(NameResource.OverMaxLength, "1000");
            revtxtKeyCommentsCN.Text = string.Format(NameResource.OverMaxLength, "1000");
            revtxtDemoContenEN.Text = string.Format(NameResource.OverMaxLength, "1000");
            revtxtDemoStepEN.Text = string.Format(NameResource.OverMaxLength, "1000");
            revtxtKeyCommentsEN.Text = string.Format(NameResource.OverMaxLength, "1000");
            rfvtxtChName.ErrorMessage = ManageResource.mgr_lblProductNameCN + CommonResource.NotNull;
            rfvtxtEnName.ErrorMessage = ManageResource.mgr_lblProductNameEN + CommonResource.NotNull;
        }

        protected void btnSubmitPro_Click(object sender, EventArgs e)
        {
            lblUploadMessage.Text = string.Empty;
            if (chkChinese.Checked == false && chkEnglish.Checked == false)
            {
                lblErrmessage.Text = NameResource.Language + CommonResource.NotNull;
                return;
            }
            else
            {
                switch (PageStatus)
                {
                    case Utility.PageStatus.Edit:
                        Model.Product obj = ProductPresent.GetById(Id);
                        obj.LabId = int.Parse(ucLocationLab.LabValue);
                        obj.Name_CN = txtChName.Text;
                        obj.Name_EN = txtEnName.Text;
                        obj.DemoType_CN = Server.HtmlEncode(txtDemoTypeCN.Text);
                        obj.DemoContent_CN = Server.HtmlEncode(txtDemoContenCN.Text);
                        obj.DemoStep_CN = Server.HtmlEncode(txtDemoStepCN.Text);
                        obj.KeyComments_CN = Server.HtmlEncode(txtKeyCommentsCN.Text);
                        obj.Equipment_CN = Server.HtmlEncode(txtEquipmentCN.Text);
                        obj.DemoType_EN = Server.HtmlEncode(txtDemoTypeEN.Text);
                        obj.DemoContent_EN = Server.HtmlEncode(txtDemoContenEN.Text);
                        obj.DemoStep_EN = Server.HtmlEncode(txtDemoStepEN.Text);
                        obj.KeyComment_EN = Server.HtmlEncode(txtKeyCommentsEN.Text);
                        obj.Equipment_EN = Server.HtmlEncode(txtEquipmentEN.Text);
                        obj.Status = (int)(rbtnInactive.Checked == true ? ProductStatus.Inactive : ProductStatus.Active);
                        obj.ChineseIntroduce = chkChinese.Checked;
                        obj.EnglishIntroduce = chkEnglish.Checked;
                        if (!uploadPicture("edit", Id))
                            return;
                        ProductPresent.Update(obj);
                        //邮件通知，并将对该产品的申请置为草稿
                        if (rbtnInactive.Checked)
                        {
                            var mailproductid = Id;
                            var productCN = txtChName.Text;
                            var productEN = txtEnName.Text;
                            toEmailNotification(mailproductid, productCN, productEN);
                        }
                        Response.Redirect("/Product/View.aspx");
                        break;
                    case Utility.PageStatus.New:
                        var labid = int.Parse(ucLocationLab.LabValue);
                        var chname = this.txtChName.Text;
                        var enname = this.txtEnName.Text;
                        var demotypecn = Server.HtmlEncode(txtDemoTypeCN.Text);
                        var democontentcn = Server.HtmlEncode(txtDemoContenCN.Text);
                        var demostepcn = Server.HtmlEncode(txtDemoStepCN.Text);
                        var demokeycommentcn = Server.HtmlEncode(txtKeyCommentsCN.Text);
                        var equipmentcn = Server.HtmlEncode(txtEquipmentCN.Text);
                        var demotypeen = Server.HtmlEncode(txtDemoTypeEN.Text);
                        var democontenten = Server.HtmlEncode(txtDemoContenEN.Text);
                        var demostepen = Server.HtmlEncode(txtDemoStepEN.Text);
                        var demokeycommenten = Server.HtmlEncode(txtKeyCommentsEN.Text);
                        var equipmenten = Server.HtmlEncode(txtEquipmentEN.Text);
                        var status = (int)(rbtnInactive.Checked == true ? ProductStatus.Inactive : ProductStatus.Active);
                        Model.Product product = new Model.Product()
                        {
                            LabId = labid,
                            Name_CN = chname,
                            Name_EN = enname,
                            DemoType_CN = demotypecn,
                            DemoContent_CN = democontentcn,
                            DemoStep_CN = demostepcn,
                            KeyComments_CN = demokeycommentcn,
                            Equipment_CN = equipmentcn,
                            DemoType_EN = demotypeen,
                            DemoContent_EN = democontenten,
                            DemoStep_EN = demostepen,
                            KeyComment_EN = demokeycommenten,
                            Equipment_EN = equipmenten,
                            ChineseIntroduce = chkChinese.Checked,
                            EnglishIntroduce = chkEnglish.Checked,
                            Status = status
                        };
                        ProductPresent.Create(product);
                        if (!uploadPicture("new", product.ProductId))
                        {
                            ProductPresent.Delete(product.ProductId);
                            return;
                        }
                        Response.Redirect("/Product/View.aspx");
                        break;
                }
            }
        }

        protected bool uploadPicture(string status, int productid)
        {
            if (string.IsNullOrWhiteSpace(PicFileUpload.FileName) == false)
            {
                string fileExt = System.IO.Path.GetExtension(PicFileUpload.FileName).ToLower();
                string extstr = string.Empty;
                string errorstr = string.Empty;
                bool exit = false;
                string[] extList = ConfigurationManager.AppSettings["Picture"].Split(',');
                foreach (string extItem in extList)
                {
                    extstr = extstr + "\\" + extItem;
                    if (fileExt == "." + extItem)
                    {
                        exit = true;
                    }
                }
                errorstr = " : " + NameResource.SysSupportPictureExp + extstr;
                if (exit)
                {
                    try
                    {
                        string filename = PicFileUpload.FileName;
                        Random random = new Random();
                        var random1 = 10000 + random.Next(1, 90000);
                        string picturename = DateTime.Now.ToString("yyMMddHHmmss") + random1 + "-" + filename;
                        string mapPath = Server.MapPath("/UploadImages");
                        string webFilePath = Path.Combine(mapPath, picturename);
                        if (!Directory.Exists(mapPath))
                        {
                            Directory.CreateDirectory(mapPath);
                        }
                        PicFileUpload.SaveAs(webFilePath);
                        string path = "../UploadImages/" + picturename;
                        if (status.Equals("new"))
                        {
                            Model.ProductPic productpic = new Model.ProductPic()
                            {
                                ProductId = productid,
                                Path = path,
                            };
                            ProductPicPresent.Create(productpic);
                        }
                        else if (status.Equals("edit"))
                        {
                            var productpic = ProductPicPresent.GetByCondition(g => g.ProductId == productid);
                            if (productpic == null)
                            {
                                Model.ProductPic productpict = new Model.ProductPic()
                                {
                                    ProductId = productid,
                                    Path = path,
                                };
                                ProductPicPresent.Create(productpict);
                            }
                            else
                            {
                                productpic.Path = path;
                                ProductPicPresent.Update(productpic);
                            }
                        }
                        return true;
                    }
                    catch (Exception ex)
                    {
                        lblUploadMessage.Text = NameResource.Upload_Fail + " : " + ex.Message;
                        return false;
                    }
                }
                else
                {
                    lblUploadMessage.Text = NameResource.Upload_Fail + errorstr;
                    return false;
                }
            }
            else
            {
                return true;
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("/Product/View.aspx");
        }

        //邮件通知，并将对该产品的申请置为草稿
        protected void toEmailNotification(int productid, string productCN, string productEN)
        {
            int statusPending = (int)RequestStatus.Pending;
            int statusApproved = (int)RequestStatus.Approved;
            int statusAskForMore = (int)RequestStatus.AskForMore;
            var product = ProductPresent.GetList();
            var visitProduct = VisitProductPresent.GetList(g => g.ProductId == productid);
            var visitRequest = VisitRequestPresent.GetList();
            var request = RequestPresent.GetList();
            var result = (from p in product
                          from vp in visitProduct
                          from vr in visitRequest
                          from r in request
                          where p.ProductId == vp.ProductId && vp.VisitRequestId == vr.VisitRequestId && vr.RequestId == r.RequestId && (r.Status == statusPending || r.Status == statusApproved || r.Status == statusAskForMore)
                          select new 
                          { 
                              r.RequestId,
                              r.RequestUserId
                          }
                          );
            if (result != null)
            {
                foreach (var r in result)
                {
                    var requestedit = RequestPresent.GetById(r.RequestId);
                    if (requestedit != null)
                    {
                        requestedit.Status = (int)RequestStatus.Draft;//申请改为草稿 
                        RequestPresent.Update(requestedit);
                    }

                    var user = UserPresent.GetById(r.RequestUserId);
                    if (user != null)
                    {
                        string managerEmail = string.Empty;
                        string managerTel = string.Empty;
                        string nameCN = string.Empty;
                        string nameEN = string.Empty;
                        RequestPresent.GetUserNameById(user.UserId, out nameCN, out nameEN);
                        RequestPresent.GetEmailPhoneById(CurrentUserId, out managerEmail, out managerTel);

                        string content = nameEN + "^" + productEN + "^" + managerEmail + "^" + managerTel + "^" + nameCN + "^" + productCN + "^" + managerEmail + "^" + managerTel;
                        MailPresent.SendMail(EmailTemplate.ProductInactiveReminder, content, user.Email, "");
                    }
                }
            }
        }

    }
}